﻿@using SharedClasses
@using WebApiFromServerApp.Services
@inject WeatherForecastServiceForWebApi _service

<h3>URL to POST to: @ActionUrl</h3>

<TelerikGrid Data=@GridData TotalCount=@Total OnRead=@ReadItems Groupable="true"
             FilterMode=@GridFilterMode.FilterMenu Sortable=true Pageable=true Height="300px">
    <GridColumns>
        <GridColumn Field="Id" FieldType="@(typeof(int))" Title="Id" Width="100px" Groupable="false" />
        <GridColumn Field="Date" FieldType="@(typeof(DateTime))">
            <Template>
                @((context as WeatherForecast).Date.ToString("dddd, dd MMM yyyy"))
            </Template>
        </GridColumn>
        <GridColumn Field="TemperatureC" FieldType="@(typeof(int))" Title="Temp. C" />
        <GridColumn Field="TemperatureF" FieldType="@(typeof(int))" Title="Temp. F" />
        <GridColumn Field="Summary" FieldType="@(typeof(string))" />
    </GridColumns>
</TelerikGrid>

@code {
    [Parameter] public string ActionUrl { get; set; }
    public List<object> GridData { get; set; }
    public int Total { get; set; } = 0;

    protected async Task ReadItems(GridReadEventArgs args)
    {
        // we pass the request to the service, and there Telerik DataSource Extension methods will shape the data
        // then the service returns our project-specific envelope so that the data can be serialized by the framework
        DataEnvelope<WeatherForecast> result = await _service.GetData(args.Request, ActionUrl);

        if (args.Request.Groups.Count > 0)
        {
            var data = GroupDataHelpers.DeserializeGroups<WeatherForecast>(result.GroupedData);
            GridData = data.Cast<object>().ToList();
        }
        else
        {
            GridData = result.CurrentPageData.Cast<object>().ToList();
        }

        Total = result.TotalItemCount;

        StateHasChanged();
    }
}